package com.example.backend.security.custom;

import com.example.backend.entitly.mysql.user.UserAuth;
import com.example.backend.security.SecurityUser;
import com.example.backend.service.mysql.permission.PermissionService;
import com.example.backend.service.mysql.user.UserAuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
@RequiredArgsConstructor
public class CustomDetailsService {

    private final UserAuthService userAuthService;
    private final PermissionService permissionService;
    private final PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String username, String password) throws UsernameNotFoundException {
        UserAuth byUsername = userAuthService.getByUsername(username);
        if (byUsername == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (!passwordEncoder.matches(password, byUsername.getCredential())) {
            throw new UsernameNotFoundException("密码错误");
        }
        Collection<SimpleGrantedAuthority> authorities = permissionService.getByAuthorities(byUsername.getUserId());
        return new SecurityUser(byUsername.getIdentifier(), byUsername.getCredential(), authorities, byUsername.getIsActive().equals(1),
                true, true, true, byUsername.getUserId());
    }
}
